package com.aierkeji.call.cms.util;

import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.util.CollectionUtils;


public class AppConfig {
	private static final Logger log = LoggerFactory.getLogger(AppConfig.class);

//	private static  Environment properties = null;
	private static  LinkedHashMap<String, Object> properties  = new LinkedHashMap<>();

	public static void builder(Environment properties) {
		AbstractEnvironment ab = (AbstractEnvironment)properties;
		MutablePropertySources property = ab.getPropertySources();
		property.forEach(k->{
			if(k.getName().contains("application-akj.properties")) {
				log.info("file name:{}",k.getName());
				LinkedHashMap<String, Object> source = (LinkedHashMap)k.getSource();
				if(!CollectionUtils.isEmpty(source)) {
					source.forEach((k1,v)->{
						log.info("key:{}-----value :{}",k1,v.toString());
					});
				}
				AppConfig.properties = source;
			}
		});
		
	}
	
	


	public static String getProperty(String key) {
		return getProperty(key, null);
	}

	public static String getProperty(String key, String defaultValue) {
		try {
			return properties.containsKey(key)?properties.get(key).toString():defaultValue;
//			return properties.getProperty(key, defaultValue);
		} catch (Exception e) {
			log.error("",e);
			return defaultValue;
		}
	}

	public static String getPropertyEncoding(String key, String encoding) {
		return getPropertyEncoding(key, encoding, null);
	}

	public static String getPropertyEncoding(String key, String encoding, String defaultValue) {
		String str = getProperty(key, defaultValue);
		try {
			// 进行编码转换，解决问题
			str = new String(str.getBytes("ISO8859-1"), encoding);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage(), e);
		}
		return str;
	}

}